package org.su.webadapter.velocity;


import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;
import java.io.*;
import java.net.URL;

public class HtmlProcessor extends HTMLEditorKit.ParserCallback {
	  StringBuffer textBuffer;
	  Reader reader;
	  
	  public HtmlProcessor() {  
	  }  
	  
	  public HtmlProcessor(Reader r) {
	    reader = r;  
	  }  
	  
	  public void parse() throws IOException {
	    textBuffer = new StringBuffer();
	    ParserDelegator parserDelegator = new ParserDelegator();
	    parserDelegator.parse(reader, this, true);  
	  }  
	  
	  public void handleText(char[] text, int pos) {  
	    textBuffer.append(text);  
	  }  
	  
	  public StringBuffer getTextBuffer() {
	    return textBuffer;  
	  }  
	  
	  public void setTextBuffer(StringBuffer textBuffer) {
	    this.textBuffer = textBuffer;  
	  }  
	  
	  public static String htmlToPlainText(String html) {
	    StringReader sr = new StringReader(html);
	  
	    HtmlProcessor d = new HtmlProcessor(sr);  
	    try {  
	      d.parse();  
	    } catch (IOException e) {
	      // TODO Auto-generated catch block  
	      e.printStackTrace();  
	    }  
	  
	    sr.close();  
	    String result = d.getTextBuffer().toString();
	    sr = null;  
	    d = null;  
	    return result;  
	  }  
	  
	  public static void main(String[] argv) {
	    try {  
	      // the HTML to convert  
	      URL toRead;
	      if (argv.length == 1)  
	        toRead = new URL(argv[0]);
	      else  
	        toRead = new URL("http://www.hecks.tk");
	  
	      BufferedReader in = new BufferedReader(new InputStreamReader(toRead
	          .openStream()));  
	      HtmlProcessor processor = new HtmlProcessor(in);  
	      processor.parse();  
	      in.close();  
	  
	      System.out.println(processor.getTextBuffer());
	    } catch (Exception e) {
	      e.printStackTrace();  
	    }  
	  }  
	}  
